import React, { Component } from 'react';
import { Form, Input, Button, Checkbox, message } from 'antd';
import { connect } from 'react-redux';
import { Navigate } from 'react-router-dom';
import { createSaveUserInfoAction } from '../../redux/action_craetors/login_action';
import store from '../../redux/store';
import './css/login.less';
import { reqLogin, sendEmailVerificationCode, verifyAuth } from '../../api/index.js';
import { meshLog, SPRemove, SPGet, SPSet } from "../../config";
import 'antd/dist/antd.less';
import logo from '../../static/login/logo.png';
import beijing from '../../static/login/beijing.png';
import PubSub from 'pubsub-js';

const { Item } = Form;

class Login extends Component {
    state = {
        isLogin: false,
        isForgotPassword: false,
        countdown: 0,
    };

    // 创建 Form 引用
    formRef = React.createRef();

    // 登录表单提交
    handleSubmit = async (values) => {
        const { passwd, email } = values;
        const platform = 0;
        const deviceNo = "1122334455667788"
        let result = await reqLogin(email, passwd, platform, deviceNo);
        const { code, msg } = result;
        meshLog('result', result);
        //if (code === 0 && msg.meshList.length > 0) {
        if (code === 0) {
            const date = {
                token: msg.token,
                //meshList: msg.meshList,
                useName: msg.name,
                isLogin: true,
                createTime: msg.createTime,
                name: msg.name,
                email: email
            };
            store.dispatch(createSaveUserInfoAction(date));
            this.setState({ isLogin: true });
            PubSub.publish('kaiqi', '');
        } else {
            message.warning('Account password information error', 1);
        }
    };

    // 找回密码提交
    save = async (value) => {

        const { password1, password2, email, verificationCode } = value;
        const pwd = password1
        const code = verificationCode
        // meshLog('Reset password for', email, 'with code', verificationCode);
        if (!email || !verificationCode || !password1 || !password2) {
            message.warning('Please complete all fields');
            return;
        }

        if (password1 !== password2) {
            message.error('Passwords do not match!');
            return;
        }

        let result = await verifyAuth(email, code, pwd);

        if (result.code === 0) {
            message.success('Password has been reset!');
            this.setState({ isForgotPassword: false });
        }
        else {
            message.warning('Password not successfully changed');
        }


    };

    // 获取验证码
    sendCode = async () => {
        const email = this.formRef.current?.getFieldValue('email');
        if (!email) {
            message.warning('Please input your email address first.');
            return;
        }

        meshLog('Sending verification code to:', email);

        try {
            // 示例：发送验证码的 API
            // await reqSendVerificationCode(email);
            let result = await sendEmailVerificationCode(email);
            meshLog('result', result);

            if (result.code === 0) {
                message.success('Verification code sent!');
            }
            else {
                message.warning('Please check your email address first.');
            }


            this.setState({ countdown: 60 }, () => {
                this.countdownInterval = setInterval(() => {
                    this.setState((prev) => {
                        if (prev.countdown <= 1) {
                            clearInterval(this.countdownInterval);
                            return { countdown: 0 };
                        }
                        return { countdown: prev.countdown - 1 };
                    });
                }, 1000);
            });
        } catch (error) {
            message.error('Failed to send verification code.');
        }
    };

    // 切换界面
    showForgotPassword = () => {
        this.setState({ isForgotPassword: true });
    };

    showLogin = () => {
        this.setState({ isForgotPassword: false });
    };

    componentWillUnmount() {
        clearInterval(this.countdownInterval);
    }

    render() {
        const { isLogin, isForgotPassword, countdown } = this.state;

        if (isLogin) {
            return <Navigate replace to="/admin" />;
        }

        return (
            <div className="login-container">
                <div className="login-left">
                    <img src={beijing} alt="background" className="bg-image" />
                </div>
                <div className="login-right">
                    <div className="login-box">
                        {!isForgotPassword ? (
                            <Form
                                name="login"
                                layout="vertical"
                                onFinish={this.handleSubmit}
                                requiredMark={false}
                            >
                                <img src={logo} alt="logo" className="logo" />
                                <h2 className="title">Welcome HSE WISE</h2>
                                <Item
                                    name="email"
                                    rules={[{ required: true, message: 'Please input your email!' }]}
                                >
                                    <Input className="email" placeholder="*Email Address" />
                                </Item>
                                <Item
                                    name="passwd"
                                    rules={[{ required: true, message: 'Please input your password!' }]}
                                >
                                    <Input.Password className="password" placeholder="*Password" />
                                </Item>
                                <Item name="agreement" valuePropName="checked">
                                    <Checkbox className="agreement">
                                        I have read the <a href="123123">Terms and Conditions</a>
                                    </Checkbox>
                                </Item>
                                <Item>
                                    <Button type="primary" htmlType="submit" block className="submit-btn">
                                        SIGN IN
                                    </Button>
                                </Item>
                                <div className="forgot" onClick={this.showForgotPassword}>
                                    Forgot Password?
                                </div>
                                <div className="footer">
                                    ©2025 <span className="highlight">HAISEN</span> | <span className="highlight">HSE</span> All Rights Reserved
                                </div>
                            </Form>
                        ) : (
                            <Form
                                ref={this.formRef}
                                name="forgot-password"
                                layout="vertical"
                                requiredMark={false}
                                onFinish={this.save}
                            >
                                <h1 style={{ textAlign: 'left' }}>Forgot Password?</h1>
                                <h4 style={{ textAlign: 'left' }}>Enter the email address you used when you</h4>
                                <h4 style={{ textAlign: 'left' }}>joined, and we will send you a verification</h4>
                                <h4 style={{ textAlign: 'left' }}>code to reset your password.</h4>
                                <Item
                                    name="email"
                                    rules={[{ required: true, message: 'Please input your email!' }]}
                                >
                                    <Input style={{ height: 45, borderRadius: 8 }} placeholder="*Email Address" />
                                </Item>
                                <Item
                                    name="verificationCode"
                                    rules={[{ required: true, message: 'Please input the verification code!' }]}
                                >
                                    <div style={{ display: 'flex' }}>
                                        <Input style={{ width: 210, height: 45, borderRadius: 8 }} placeholder="*Verification Code" />
                                        <Button
                                            type="primary"
                                            onClick={this.sendCode}
                                            disabled={countdown > 0}
                                            style={{ width: 120, marginLeft: 20, height: 45, borderRadius: 8, backgroundColor: '#0a46bd' }}
                                        >
                                            {countdown > 0 ? `${countdown}s` : 'Send Code'}
                                        </Button>
                                    </div>
                                </Item>
                                <Item
                                    name="password1"
                                    rules={[{ required: true, message: 'Please input your password!' }]}
                                >
                                    <Input.Password className="password" placeholder="*8-12 characters, letters & numbers" />
                                </Item>
                                <Item
                                    name="password2"
                                    rules={[{ required: true, message: 'Please confirm your password!' }]}
                                >
                                    <Input.Password className="password" placeholder="*Confirm new password" />
                                </Item>
                                <Item>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <Button
                                            type="primary"
                                            onClick={this.showLogin}
                                            style={{ width: 150, height: 45, borderRadius: 8, backgroundColor: '#0a46bd' }}
                                        >
                                            Back to Login
                                        </Button>
                                        <Button
                                            type="primary"
                                            htmlType="submit"
                                            style={{ width: 150, height: 45, borderRadius: 8, backgroundColor: '#0a46bd' }}
                                        >
                                            SAVE
                                        </Button>
                                    </div>
                                </Item>
                            </Form>
                        )}
                    </div>
                </div>
            </div>
        );
    }
}

export default connect(
    state => ({}),
    {
        saveUserInfo: createSaveUserInfoAction,
    }
)(Login);
